import { createRouter, createWebHistory } from "vue-router";

const layout = () => import("../page/pages/layout/index.vue");
const UserList = () => import("../page/pages/user/List.vue");
const UserDetail = () => import("../page/pages/user/Detail.vue");
const Login = () => import("../page/pages/login/index.vue");

const routerInstance = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      component: Login,
      meta: {
        title: "登录",
      },
    },
    {
      path: "/",
      component: layout,
      children: [
        {
          path: "user",
          children: [
            {
              path: "list",
              meta: { title: "用户列表" },
              name: "userList",
              component: UserList,
            },
            {
              path: "detail",
              meta: { title: "用户详情" },
              component: UserDetail,
            },
          ],
        },
      ],
    },
  ],
});

routerInstance.beforeEach((to, from) => {
  const api = to.query.api;
  if (api) {
    sesstionStorage.api = api;
  }
  // 没有登录，只能访问login页面
  if (to.path !== "/login" && !localStorage.token) {
    return "/login";
  }
  // 成功登录，不能访问login页面
  if (to.path === "/login" && localStorage.token) {
    return "/user/list";
  }
  // 自动添加title
  document.title = to.meta.title || "";
});

export default routerInstance;
